package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import dao.ProductDao;
import domain.Order;
import domain.OrderItem;
import domain.Product;
import domain.User;
import exception.RegisterException;
import service.OrderService;
import service.ProductService;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class OrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //第一步：提取参数
        JSONObject object = null;
        Response build = null;
        ProductDao service = null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
            JSONArray cart = object.getJSONArray("cart");
            JSONObject info = object.getJSONObject("info");
            double totalPrice = 0;
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            for (int i = 0; i < cart.size(); i++) {
                JSONObject goods = (JSONObject) cart.get(i);
                String id = goods.getString("id");
                double lineTotal = goods.getDoubleValue("lineTotal");
                totalPrice += lineTotal;
                service = new ProductDao();
                Product book = service.findProductById(id);
                if (book.getPnum() < goods.getIntValue("number")) {
                    build = Response.build(ResponseCode.ERROR, book.getName() + "商品订购数量超出库存！当前库存为：" + book.getPnum());
                    resp.setContentType("application/json;charset=utf-8");
                    resp.getWriter().write(JSON.toJSON(build).toString());
                    return;
                }
            }
            OrderService orderService = new OrderService();
            Order order = new Order();
            order.setId(UUID.randomUUID().toString());//随机ID
            order.setMoney(totalPrice);//小计
            order.setReceiverAddress(info.getString("address"));//地址
            order.setReceiverName(info.getString("name"));//姓名
            order.setReceiverPhone(info.getString("phone"));//电话号码
            order.setPaystate(0);//是否付款，0为未付款
            order.setUser(user);
            List<OrderItem> orderItemList = new ArrayList<OrderItem>();
            for (int i = 0; i < cart.size(); i++) {//这个循环是插入订单项
                JSONObject goods = (JSONObject) cart.get(i);
                String id = goods.getString("id");
                Product book = service.findProductById(id);
                int number = goods.getIntValue("number");
                OrderItem orderItem = new OrderItem();
                orderItem.setOrder(order);
                orderItem.setBuynum(number);
                orderItem.setP(book);
                orderItemList.add(orderItem);
            }
            order.setOrderItems(orderItemList);
            orderService.commitOrder(order);//提交订单
            build = Response.build(ResponseCode.SUCCESS);//操作成功
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
        } catch (Exception e) {
            e.printStackTrace();
            build = Response.build(ResponseCode.ERROR_PARAMS);//请求参数格式对不对或类型不对或缺失参数项！
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
    }
}

;